package com.codebox.activity;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.codebox.R;
import com.codebox.bean.Code;
import com.codebox.update.DownloadService;
import com.codebox.utils.Utils;
import com.lib.BaseActivity;
import com.lib.EventBus;
import com.lib.HttpUtil;
import com.morgoo.helper.Log;

public class CodeActivity extends BaseActivity {
	private static final String TAG = "CodeActivity";
    private Button runButton;
	public EventBus mViewController;
    private	ProgressDialog mProgressDialog;
    private Code mCode;
    private TextView titleText;
    private TextView sourceUrlText;
    private TextView codeDescriptionText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mViewController = EventBus.getInstance();
        setConttentViewAndToolbar(R.layout.activity_code, "代码");
        showBackHomeButton();
		mCode =(Code)getIntent().getSerializableExtra("code");
		setTitle(mCode.getTitle());

		//retive views
		titleText = (TextView)findViewById(R.id.title);
		sourceUrlText = (TextView)findViewById(R.id.source);
		codeDescriptionText = (TextView)findViewById(R.id.descrip);
		titleText.setText(mCode.getTitle());
		sourceUrlText.setText(mCode.getSourceUrl());
		codeDescriptionText.setText(mCode.getDescription());

		runButton = (Button)findViewById(R.id.run);
		runButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v){
				downLoadPlugin();
			}
		});
		sourceUrlText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v){
				if(sourceUrlText.getText()!= null && !sourceUrlText.getText().equals("")){
					Uri uri = Uri.parse(sourceUrlText.getText().toString());
			        Intent it = new Intent(Intent.ACTION_VIEW, uri);
			        it.setData(uri);
			        it.setAction( Intent.ACTION_VIEW);
			        startActivity(it);
				}
			}
		});

		// instantiate it within the onCreate method
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage("正在下载");
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setCancelable(true);
		mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
		    @Override
		    public void onCancel(DialogInterface dialog) {

		    }
		});
		mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// TODO Auto-generated method stub

			}
		});
	}

	public void downLoadPlugin() {
		String pluginUrl = mCode.getPluginUrl();
        Log.d(TAG,"downlaod plugin url="+pluginUrl);
        if(Utils.isExternalStorageWritable()) {
            //getExternalStorageDirectory
			String dir = getExternalFilesDir("plugin").getAbsolutePath();
			File folder = Environment.getExternalStoragePublicDirectory(dir);
			if(!folder.exists() || !folder.isDirectory()) {
                folder.mkdirs();
			}
			String filename = pluginUrl.substring(pluginUrl.lastIndexOf("/"),pluginUrl.length());
			Log.i(TAG,"filename = " + filename);
			String destinationFilePath =  dir + "/" + filename;
			File file = new File(destinationFilePath);
			if(file.exists() && file.isFile()){//运行插件

                loadPluginToHost();
				return;
			}
			if(!HttpUtil.isNetworkConnected()){
				Toast.makeText(this, "无网络链接，无法下载插件", 100).show();
				return;
			}
			mProgressDialog.show();
			Intent intent = new Intent(this, DownloadService.class);
			intent.putExtra("url", pluginUrl);
			intent.putExtra("dest", destinationFilePath);
			intent.putExtra("receiver", new DownloadReceiver(new Handler()));
			startService(intent);
	    }else {
	    	Toast.makeText(this, "无法获得读写权限（是不是手机连着电脑，拔下来试试）", 300).show();
	    	return;
	    }
	}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

	public void loadPluginToHost() {
        Intent it=new Intent(this,ApkListActivity.class);
        startActivity(it);
//		String pluginUrl = mCode.getPluginUrl();
//		String dir = getExternalFilesDir( "plugin").getAbsolutePath();
//		String filename = pluginUrl.substring(pluginUrl.lastIndexOf("/"),pluginUrl.length());
//		File plugin = new File (dir,  filename);
//        PluginItem item = new PluginItem();
//        item.pluginPath = plugin.getAbsolutePath();
//        item.packageInfo = DLUtils.getPackageInfo(this, item.pluginPath);
//        if (item.packageInfo.activities != null && item.packageInfo.activities.length > 0) {
//            item.launcherActivityName = item.packageInfo.activities[0].name;
//        }
//        DLPluginManager pluginManager = DLPluginManager.getInstance(this);
//        pluginManager.loadApk(item.pluginPath);
//        pluginManager.startPluginActivity(this, new DLIntent(item.packageInfo.packageName, item.launcherActivityName));
	}

    @SuppressLint("ParcelCreator")
    private class DownloadReceiver extends ResultReceiver{
        public DownloadReceiver(Handler handler) {
            super(handler);
        }
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            if (resultCode == DownloadService.UPDATE_PROGRESS) {
                int progress = resultData.getInt("progress");
                mProgressDialog.setProgress(progress);
                if (progress == 100) {
                	Log.i("progress","progress = 100");
                	loadPluginToHost();
                    mProgressDialog.dismiss();
                }
            }
        }
    }
}
